package com.zh.juc.thread;

import java.util.concurrent.*;

/**
 * @Author: zhanghuan
 * @date: 2022/10/6 13:43
 * @description: create it
 */
public class FutureThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 3个任务，只有一个主线程
        // m1();
        // 3个任务，多线程

        m2();
    }

    private static void m2() throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        long startTime = System.currentTimeMillis();
        FutureTask<String> futureTask1 = new FutureTask<String>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task1";
        });
        threadPool.submit(futureTask1);
        System.out.println(futureTask1.get());

        FutureTask<String> futureTask2 = new FutureTask<String>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task2";
        });
        threadPool.submit(futureTask2);
        System.out.println(futureTask2.get());

        try {
            TimeUnit.MILLISECONDS.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime + "毫秒");
    }

    private static void m1() {
        long startTime = System.currentTimeMillis();
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.MILLISECONDS.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime + "毫秒");
    }
}